<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <div class="logo">
          <el-icon><Monitor /></el-icon>
          <h1>Summer Boss</h1>
        </div>
        <div class="welcome-text">
          <h2>欢迎回来</h2>
          <p>登录您的账户以继续</p>
        </div>
      </div>

      <el-form :model="form" @submit.prevent="handleLogin">
        <el-form-item>
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="form.rememberMe">记住我</el-checkbox>
          <el-link type="primary" class="forget-pwd">忘记密码？</el-link>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            :loading="loading"
            class="login-button"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '../api/auth'
import { User, Lock, Monitor } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loading = ref(false)

const form = reactive({
  username: '',
  password: '',
  rememberMe: true
})

const handleLogin = async () => {
  if (!form.username || !form.password) {
    ElMessage.error('请输入用户名和密码')
    return
  }

  loading.value = true

  const result = await login({
    username: form.username,
    password: form.password,
    rememberMe: form.rememberMe
  })

  if (result) {
    router.push('/user')
  } else {
    loading.value = false
  }
}

// 检查是否有记住的用户名
const rememberedUsername = localStorage.getItem('username')
if (rememberedUsername) {
  form.username = rememberedUsername
  form.rememberMe = true
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--el-bg-color-page);
}

.login-card {
  width: 400px;
  padding: 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  color: var(--el-color-primary);
}

.logo .el-icon {
  font-size: 24px;
  margin-right: 8px;
}

.logo h1 {
  font-size: 24px;
  margin: 0;
}

.welcome-text h2 {
  font-size: 20px;
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
}

.welcome-text p {
  color: var(--el-text-color-secondary);
}

.login-button {
  width: 100%;
}

.forget-pwd {
  float: right;
}
</style>